<template>
  <div
    @dragover.prevent="handleDragOver"
    @dragleave.prevent="handleDragLeave"
    @drop.prevent="handleDrop"
    class="base"
  >
    <slot :for="id"></slot>
    <!-- <label class="def-btn" for="forFile" style="width: 30%; margin-top: 30px">选择文件</label> -->
    <input
      type="file"
      :id="id"
      :accept="accept"
      ref="selectedFile"
      @change="handleFileSelect"
      style="display: none"
    />
    <slot name="bottom"></slot>
  </div>
</template>
<script setup lang="ts" name="MySelectFileView">
import MyApi from '@/api/apis'
import { log } from '@/utils/com'
import { isApiOk, isEmpty } from '@/utils/httputils'
import { computed, ref, watch } from 'vue'
import { toast } from './toast/my-toast'
//
const props = defineProps(['id', 'accept'])
//声明回调事件，执行回调事件:emit('onClick')
const emit = defineEmits(['callback', 'dragChange'])
// 拖拽状态
const isDragging = ref(false)
const selectedFile = ref<File | null>()
let inputElement: HTMLInputElement
// 处理文件选择
const handleFileSelect = async (event: Event) => {
  // 1. 首先将event.target断言为HTMLInputElement类型
  inputElement = event.target as HTMLInputElement
  // 2. 使用可选链操作符安全获取文件列表
  const file = inputElement.files?.[0]
  // 3. 检查文件是否存在
  if (!file) return
  // 4. 处理文件
  uploadFile(file)
}
async function uploadFile(file: File) {
  selectedFile.value = file
  if (!checkFileType()) {
    toast('不支持的文件类型')
    return
  }
  log(selectedFile.value)
  const resp = await MyApi.uploadFile(selectedFile.value, (p: number) => {
    log('上传' + p)
  })
  if (isApiOk(resp) && resp.data) {
    toast(resp.message)
    emit('callback', resp.data)
  } else {
    toast(resp.message)
  }
}
// 处理拖拽进入
const handleDragOver = (e: DragEvent) => {
  isDragging.value = true
  if (e.dataTransfer) {
    e.dataTransfer.dropEffect = 'copy'
  }
}

// 处理拖拽离开
const handleDragLeave = () => {
  isDragging.value = false
}

// 处理文件拖放
const handleDrop = async (e: DragEvent) => {
  isDragging.value = false
  const files = e.dataTransfer?.files
  if (!files || files.length === 0) {
    toast('未选择文件或类型不支持')
    return
  }
  // 只处理第一个文件
  const file = files[0]
  uploadFile(file)
}
function checkFileType() {
  if ('.*' == accept.value) {
    return true
  } else {
    //.jpg
    let b = false
    const ss = (accept.value as string).toString().split(',')
    console.log('ss->', ss)
    for (let i = 0; i < ss.length; i++) {
      console.log('比较：', selectedFile.value?.name, ss[i])
      if (selectedFile.value?.name.endsWith(ss[i])) {
        b = true
        break
      }
    }
    return b
  }
}
//
const accept = computed(() => {
  //1图片，2视频，3图片+视频，4音频，5,apk
  if (isEmpty(props.accept)) {
    return '.*'
  } else {
    return props.accept
  }
})
//
watch(isDragging, () => {
  emit('dragChange', isDragging.value)
})
</script>
<style lang="css" scoped>
.base {
  display: flex;
  flex-direction: column;
}
</style>
